<template>
  <view class="shop">
    <scroll-view class="shop__swiper" :scroll-x="true" :scroll-left="scrollLeft" @scroll="onScroll">
      <view class="shop__swiper--container">
        <view v-for="(shop, index) in computedShopAbstract" :key="index" class="shop__swiper--item" @click="handleChangeShopIndex(index)">
          <circle-comp
            :animation="currentShopIndex === index"
            :animation-speed="5000"
            :percent="currentShopIndex === index ? 100 : 0"
            circle-color="#F54319"
            default-color="#fff"
            :circle-width="2"
            bg-color="#fff"
            :size="46"
          >
            <!-- 放置一个空的插槽，不展示进度信息 -->
            <template #content></template>
          </circle-comp>
          <image :src="shop.shop.logo" class="swiper-img" />
        </view>
      </view>
    </scroll-view>
    <view class="shop__bg">
      <view class="shop__info" @click="jumpShop(currentShopInfo.shop.id)">
        <view class="shop__info--name">
          <text class="name names">{{ currentShopInfo.shop.name }}</text>
          <text
            v-if="currentShopInfo.shop.shopType && currentShopInfo.shop.shopType !== 'ORDINARY'"
            class="tag"
            :style="{ background: currentShopInfo.shop.shopType === 'SELF_OWNED' ? '#F54319' : '#FD9224' }"
            >{{ ShopTypeEnum[computedShopAbstract[currentShopIndex].shop.shopType as keyof typeof ShopTypeEnum] }}</text
          >
        </view>
        <view class="shop__info--link">进入店铺</view>
      </view>
      <scroll-view :scroll-x="true" style="height: 400rpx">
        <view class="shop__goods">
          <view
            v-for="(good, goodIndex) in currentShopInfo.goods"
            :key="goodIndex"
            class="shop__goods--item"
            @click="jumpGoods(currentShopInfo.shop.id, good.id)"
          >
            <image :src="good.logo" class="img" />
            <view class="name">{{ good.name }}</view>
            <view class="price">
              <text class="currency">￥</text>
              <text class="price-main">{{ Number(good.price).toFixed(2) }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, computed, nextTick, watch } from 'vue'
import goods from './goods.vue'
import type { PropType } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { doGetRetrieveCommodity } from '@/apis/good'
import { doGetCommodityByShop } from '@/apis/o2oshop'
import circleComp from './circle.vue'
import { doPostShopInfo } from '@/apis/good'
import { jumpGoods } from '@/utils/navigateToShopInfo'

const scrollLeft = ref(0)
enum ShopTypeEnum {
  SELF_OWNED = '自营',
  PREFERRED = '优选',
  ORDINARY = '普通',
}
interface IGoodInterface {
  name: string
  id: string
  onlyId: string
  logo: string
  price: Long
}
interface ShopInfo {
  shop: {
    name: string
    id: string
    logo: string
  }
  goods: IGoodInterface[]
}
const props = defineProps({
  shopAbstract: {
    type: Array as PropType<ShopInfo[]>,
    default: () => [],
  },
})
const computedShopAbstract = ref(props.shopAbstract?.map((item) => ({ ...item, shop: { ...item.shop, shopType: '' } })))

const jumpShop = (shopId = '') => {
  uni.navigateTo({
    url: `/basePackage/pages/merchant/Index?shopId=${shopId}`,
  })
}
const currentShopInfo = computed(() => computedShopAbstract.value[currentShopIndex.value])
const currentShopIndex = ref(0)
const globalInterval = ref<any>(null)
const computedCurrentShopCheckedData = () => {
  const scrollViewWidth = 355
  if (computedShopAbstract.value.length) {
    globalInterval.value = setInterval(() => {
      if (currentShopIndex.value === computedShopAbstract.value.length - 1) {
        currentShopIndex.value = 0
        scrollLeft.value = 0
      } else {
        currentShopIndex.value++
        if (currentShopIndex.value * 66 + 50 > scrollViewWidth + scrollLeft.value) {
          scrollLeft.value = currentShopIndex.value * 66 + 50 - scrollViewWidth
        }
      }
    }, 5000)
  }
}
const onScroll = (e: any) => {
  scrollLeft.value = e.detail.scrollLeft
}
/**
 * 获取店铺基本信息
 * @param {*} shopId
 */
const { divTenThousand } = useConvert()
async function initShopInfo() {
  if (!computedShopAbstract.value?.[0]?.shop?.id) return
  const shopGoods: { [key: string]: string[] } = {}
  const goodsShop: { [key: string]: string } = {}

  const shopIds = computedShopAbstract.value.map((item) => {
    // 记录shop下面的商品id
    shopGoods[item.shop.id] = item.goods?.map((goods) => goods.onlyId).filter((onlyId) => onlyId)

    // 记录商品id上面的shop
    shopGoods[item.shop.id]?.forEach((onlyId) => {
      goodsShop[onlyId] = item.shop.id
    })

    return item.shop.id
  })

  const goods = await getGoods(goodsShop)
  const { data, code, msg } = await doPostShopInfo(shopIds)
  if (code !== 200) return uni.showToast({ title: `${msg ? msg : '获取商铺信息失败'}`, icon: 'none' })
  computedShopAbstract.value.forEach((item) => {
    data.forEach((element: any) => {
      const { name, logo, id, shopType } = element
      if (element.id === item.shop.id) {
        item.shop = { name, logo, id, shopType }
      }
    })
    if (goods) item.goods = goods[item.shop.id]
  })
  computedShopAbstract.value = computedShopAbstract.value.filter((item) => item.shop.shopType)
}

/**
 * @: 获取商品 并组合
 */
const getGoods = async (goodsShop: { [key: string]: string }) => {
  const ids = Object.keys(goodsShop)
  const { code, data } = await doGetRetrieveCommodity({ ids, searchTotalStockGtZero: true, size: ids.length })

  const goods: { [key: string]: any[] } = {}
  if (code !== 200) return uni.showToast({ icon: 'none', title: '获取商品列表失败' })

  data.list.forEach((item: any) => {
    const { id, productName, productId, pic, salePrices } = item

    const price = Array.isArray(salePrices) ? salePrices[0] : salePrices
    const obj = {
      onlyId: id,
      id: productId,
      name: productName,
      logo: pic,
      price: divTenThousand(price) as unknown as string,
    }
    if (goods[goodsShop[item.id]]) {
      goods[goodsShop[item.id]].push(obj)
    } else {
      goods[goodsShop[item.id]] = [obj]
    }
  })

  return goods
}

watch(
  () => props.shopAbstract,
  (val) => {
    initShopInfo()
    computedCurrentShopCheckedData()
  },
  { immediate: true, deep: true },
)

const handleChangeShopIndex = (index: number) => {
  if (globalInterval.value) {
    clearInterval(globalInterval.value)
    globalInterval.value = null
  }
  currentShopIndex.value = index
  computedCurrentShopCheckedData()
}
// computedCurrentShopCheckedData()
</script>
<script lang="ts">
export default {
  options: { styleIsolation: 'shared' },
}
</script>

<style scoped lang="scss">
@include b(shop) {
  padding-bottom: 20rpx;
  @include e(swiper) {
    @include m(container) {
      @include flex(flex-start);
    }
    @include m(item) {
      margin-left: 32rpx;
      position: relative;
      &:first-child {
        margin-left: 0;
      }
    }
  }
  @include e(bg) {
    margin-top: 32rpx;
    box-sizing: border-box;
    padding: 32rpx 16rpx 0 16rpx;
    border-radius: 8rpx;
    // background: linear-gradient(180deg, rgba(245, 67, 25, 0.8), rgba(244, 245, 248, 0) 100%);
    background: url('https://medusa-small-file-1253272780.cos.ap-shanghai.myqcloud.com/gruul/20231219/49a05c8ec24548b6ae8ec6106afe417e.png');
    background-size: 100% 130%;
  }
  @include e(info) {
    @include flex(space-between, center);
    @include m(name) {
      color: #fff;
      @include flex(flex-start, center);
      @include b(name) {
        font-size: 32rpx;
        line-height: 44rpx;
      }
      @include b(tag) {
        width: 56rpx;
        height: 28rpx;
        line-height: 28rpx;
        text-align: center;
        border-radius: 4rpx;
        margin-left: 12rpx;
        display: block;
        font-size: 20rpx;
      }
    }
    @include m(link) {
      width: 172rpx;
      height: 56rpx;
      border-radius: 36rpx;
      background-color: #fff;
      line-height: 56rpx;
      text-align: center;
      color: #333;
      font-size: 28rpx;
    }
  }
  &__goods {
    @include flex(flex-start);
    margin-top: 32rpx;
    @include m(item) {
      width: 222rpx;
      background-color: #fff;
      border-radius: 8rpx;
      padding: 16rpx 16rpx 12rpx;
      margin-left: 14rpx;
      &:first-child {
        margin-left: 0;
      }
      .img {
        width: 184rpx;
        height: 184rpx;
        border-top-left-radius: 8rpx;
        border-top-right-radius: 8rpx;
      }
      .name {
        margin-top: 24rpx;
        font-size: 24rpx;
        line-height: 34rpx;
        color: #333;
        height: 68rpx;
        @include utils-ellipsis(3);
        font-weight: 500;
      }
      .price {
        color: #f54319;
        font-weight: 500;
        .currency {
          font-size: 20rpx;
        }
        &-main {
          font-size: 28rpx;
          font-weight: bold;
        }
      }
    }
  }
}

@include b(swiper-img) {
  width: 72rpx;
  height: 72rpx;
  border-radius: 50%;
  position: absolute;
  top: 14rpx;
  left: 14rpx;
}
@include b(names) {
  max-width: 430rpx;
  @include utils-ellipsis(2);
  height: 50rpx;
}
</style>
